package com.zhentao.filter;


import com.zhentao.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Date 2024/4/28 15:49
 * @Author xdm
 **/

@Component
public class LoginFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //1.获取到url,判断是否是登录的url
        String url = request.getURI().getPath();
        if (url.contains("/login")) {
            //放行
            return chain.filter(exchange);
        }

        //2.说明不是登录接口，判断是否登录
        //获取token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            //token为空，重新登录
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();

        }

        //3.token获取到了，判断token是否有效
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int ep = AppJwtUtil.verifyToken(claims);
            if (ep == 1 || ep == 2) { //过期
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();

            }


        } catch (Exception e) {
            //解密失败，重新登录
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //4token是有效的
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
